import React, { useEffect, useState, useImperativeHandle } from 'react'
import { connect } from 'dva'
import TitleLine from 'components/common/titleLine'
import { Form, Input, Select, Tooltip } from 'antd'
import noImg from 'assets/no_Img.png'
import './index.less'
import { fitterInput } from 'utils/filters'

const { Option } = Select

const { TextArea } = Input

function HeadCount({ cRef, dispatch, query, getData, deviceCheck: { checkFacility, checkUser, facilityInfo, detailData }, form }) {
  const { getFieldDecorator, validateFields, setFieldsValue } = form

  const getOptionList = () => {
    dispatch({
      type: 'deviceCheck/selectOptions',
    })
  }

  // 点检员信息
  const [checkuserData, setCheckuser] = useState(null)
  const [deviceId, setDeviceId] = useState('')
  const [checkUserId, setCheckUserId] = useState('')

  useEffect(() => {
    if (query.id === undefined) {
      // 清空设备基本信息
      dispatch({
        type: 'deviceCheck/valuation',
        payload: {
          facilityInfo: [], // 设备
          checkUser: [], // 点检员
        }
      })
      return
    }
    // 给配置点检信息和配置点检员赋值
    dispatch({
      type: 'deviceCheck/valuation',
      payload: {
        facilityInfo: detailData ? detailData.deviceVo : null, // 设备
        checkUser: detailData.checkUserInfoVo ? [detailData.checkUserInfoVo] : null, // 点检员
      }
    })
    if (detailData && detailData.deviceVo) {
      setCheckuser(detailData.checkUserInfoVo)
      setFieldsValue({
        name: detailData.name,
        remark: detailData.remark,
        deviceId: detailData.deviceVo.deviceName,
        checkUser: `${detailData.checkUserInfoVo.name}(${detailData.checkUserInfoVo.groupName})`,
      })
      setCheckUserId(detailData.checkUserInfoVo.id)
      setDeviceId(detailData.deviceVo.id)
    }
  }, [detailData, dispatch, query.id, setFieldsValue])

  const handleSubmit = (e) => {
    validateFields()
      .then((value) => {
        const values = {
          name: value.name,
          remark: value.remark,
          deviceId,
          checkUser: checkUserId
        }
        getData({ ...values, checkuserData }, 'headcount')
      })
      .catch(() => { })
  }

  useImperativeHandle(cRef, () => ({
    handleSubmit
  }));

  // 设备选择
  const handleSearch = (value, e) => {
    dispatch({
      type: 'deviceCheck/getFacilityInfo',
      payload: { id: e.key }
    })
    setDeviceId(e.key)
  }

  // 点击选择点检员，展示信息；
  const handleChange = (value, e) => {
    let data = checkUser.find(item => { return item.id === Number(e.key) })
    setCheckuser(data)
    setCheckUserId(e.key)
  }

  return (
    <Form
      className="self-form"
      onSubmit={handleSubmit}
      labelAlign='right'
    >
      <div className='headcount'>
        <div className='leftBox'>
          <TitleLine title='计划基本信息' />
          <Form.Item label="计划名称">
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请输入计划名称' },
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <Input className="self-input" placeholder="请输入计划名称" maxLength={20} />
            )}
          </Form.Item>
          <Form.Item label="计划描述">
            {getFieldDecorator('remark', {
              rules: [
                { max: 20, message: '最多可输入20字' },
              ],
              getValueFromEvent: event => event.target.value.replace(fitterInput, ''),
              validateTrigger: ['onBlur', 'onChange']
            })(
              <TextArea cols={100} className="self-input" placeholder="请输入计划描述" style={{ height: '194px' }} maxLength={20} />
            )}
          </Form.Item>
        </div>
        <div className='centerBox'>
          <div className='centerSelect'>
            <TitleLine title='配置点检设备' />
            <div className="centerBox-container">
              <Form.Item label="设备选择">
                {getFieldDecorator('deviceId', {
                  rules: [{ required: true, message: '请选择设备' }],
                  validateTrigger: ['onBlur', 'onChange']
                })(
                  <Select
                    placeholder="请选择或查询设备"
                    onChange={handleSearch}
                    showSearch={true}
                    onFocus={() => getOptionList()}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {
                      checkFacility && checkFacility.length !== 0 && checkFacility.map(item => {
                        return <Option value={`${item.deviceName}（${item.deviceNo}）`} key={item.id}>{item.deviceName}（{item.deviceNo}）</Option>
                      })
                    }
                  </Select>
                )}
              </Form.Item>
              <div style={{'marginLeft': '12px', color: '#ccc', fontSize: '12px',width: 'calc(30% - 12px)',float: 'right'}}>
                <span>只可选择台账状态【启用】的设备</span>
              </div>
            </div>
          </div>
          <div className='centerfoot'>
            <div className='imgbox'>
              <img src={facilityInfo && facilityInfo.deviceImage ? facilityInfo.deviceImage : noImg} alt='' />
              <div className='imgalt' style={{ padding: '0 10px' }}>
                <span>设备状态<span className='imgalText'>{facilityInfo && facilityInfo.runStatusStr}</span></span>
                <span>台账状态<span className='imgalText'>{facilityInfo && facilityInfo.ledgerStatusStr}</span></span>
              </div>
            </div>
            <div className='mesgbox'>
              <div className='mesgboxTop'>
                <div className='mesgboTop_title'>{facilityInfo && facilityInfo.deviceName}</div>
                <span className='create_title'>创建日期</span>
                <span className='crate_time'>{facilityInfo && facilityInfo.createdTime}</span>
              </div>
              <div className='otsidebox'>
                <div className='otsidebox-box'>
                  <div className='contentbox1'>
                    <div className='titles'>设备类型</div>
                    <span className='contents'>{facilityInfo && facilityInfo.deviceTypeName}</span>
                  </div>
                  <div className='contentbox'>
                    <div className='titles'>使用部门</div>
                    {/* <Tooltip placement="top" title={facilityInfo && facilityInfo.groupName}> */}
                      <span className='contents'>{facilityInfo && facilityInfo.groupName}</span>
                    {/* </Tooltip> */}
                  </div>
                </div>
                <div className='otsidebox-box'>
                  <div className='contentbox1'>
                    <div className='titles'>设备编号</div>
                    <span className='contents'>{facilityInfo && facilityInfo.deviceNo}</span>
                  </div>
                  <div className='contentbox'>
                    <div className='titles'>责任人 </div>
                    <span className='contents'>{facilityInfo && facilityInfo.chargePerson}</span>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
        <div className='rightBox'>
          <div className='centerSelect'>
            <TitleLine title='配置点检员' />
            <div className="right-container">
              <Form.Item label="选择点检员">
                {getFieldDecorator('checkUser', {
                  rules: [{ required: true, message: '请选择点检员' }],
                  validateTrigger: ['onBlur', 'onChange']
                })(
                  <Select
                    style={{ width: '1.35rem' }}
                    placeholder="请选择"
                    onChange={handleChange}
                    showSearch={true}
                    onFocus={() => getOptionList()}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {
                      checkUser && checkUser.length !== 0 && checkUser.map(item => {
                        return <Option value={`${item.name}(${item.groupName})`} key={item.id}>{item.name}（{item.groupName}）</Option>
                      })
                    }
                  </Select>
                )}
              </Form.Item>
              <span className='seletmsg'>只可选择本企业巡检员</span>
            </div>
          </div>
          <div className='userMsg'>
            <div className='photobox'>
              <div className='photo_title'>员工头像</div>
              <div className='photo'><img src={checkuserData && checkuserData.headImage ? checkuserData.headImage : noImg} alt='' /></div>
            </div>
            <div className='msg'>
              <div className="msg-item">
                <div className='title'>姓名</div>
                <div className='text'>{checkuserData && checkuserData.name}</div>
              </div>
              <div className="msg-item">
                <div className='title'>员工编号</div>
                <div className='text'>{checkuserData && checkuserData.userNo}</div>
              </div>
              <div className="msg-item">
                <div className='title'>手机号</div>
                <div className='text'>{checkuserData && checkuserData.mobile}</div>
              </div>
              <div className="msg-item">
                <div className='title'>部门</div>
                <div className='text'>{checkuserData && checkuserData.groupName}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Form>
  )
}

export default connect(({ deviceCheck }) => ({
  deviceCheck
}))(Form.create()(HeadCount))
